import json
from flask import request, Response, render_template
from apps import  mongo
from . import core_blue

@core_blue.route("/instence", methods=["GET", "POST", "DELETE"])
def instence():
    # post -- 新增实例
    if request.method == "POST":
        jstr = request.get_data(as_text=True)
        if not jstr:
            return {"status": 400, "msg": "absent data"}
        request_body = json.loads(jstr)
        data_center = request_body.get("data_center", None)
        mon_type = request_body.get("mon_type", None)
        hosts = request_body.get("hosts", None)  # list

        # TODO 根据incetence 请求腾讯云接口获取IP:port, data_center

        if not (data_center and mon_type and hosts):
            return {"status": 400, "msg": "absent data"}

        labels = {
            "__meta_datacenter": data_center,
            "__meta_prometheus_job": mon_type
        }
        cols = mongo.db.dt_instence.find({"target": {"$in": hosts}})
        cols = [i for i in cols]
        if cols:
            addrs = ",".join([col["target"] for col in cols])
            return {"status": 400, "msg": f"{addrs} already exist"}

        documents = list()
        for host in hosts:
            ele = {"target": host}
            ele.update(labels)
            documents.append(ele)        
        mongo.db.dt_instence.insert_many(documents)

        return {"status": 200, "msg": "add success"}
    
    # delete -- 删除实例
    if request.method == "DELETE":
        jstr = request.get_data(as_text=True)
        print(jstr)
        if not jstr:
            return {"status": 400, "msg": "absent data"}
        host_port = json.loads(jstr).get("host_port")  # list
        if not host_port:
            return {"status": 400, "msg": "absent data"}
        mongo.db.dt_instence.delete_many({"target": {"$in": host_port}})
        return {"status": 200, "msg": "delete success"}

    # get -- 返回所有实例，prometheus自动发现的访问接口
    docs = mongo.db.dt_instence.find()
    rets = list()
    for doc in docs:
        print("----", doc)
        doc.pop("_id")
        host = doc.pop("target")
        for ret in rets:
            if ret["labels"] == doc:
                ret["targets"].append(host)
                break
        else:
            ret = {}
            ret["targets"] = [host]
            ret["labels"] = doc
            rets.append(ret)

    return Response(json.dumps(rets), mimetype='application/json')